<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9">
    <div class="container" style="width: 75vw;padding: 20px;padding-top: 0px;">
      <StuExamNavBar :examId="examId" :semesterId="semesterId" :showNav="true" />

      <div class="content-layout">
        <!-- 左侧部分：学生信息 + 筛选器 + 题号导航 -->
        <div class="left-panel">
          <div class="student-info">
           <img :src="studentInfo.avatar" 
              alt="学生头像" 
              class="avatar"
              style="object-fit: cover;">
            <div>
              <p>姓名：<strong>{{ studentInfo.name }}</strong></p>
              <p>学号：<strong>{{ studentInfo.number }}</strong></p>
              <p>学校：<strong>{{ studentInfo.class }}</strong></p>
            </div>
            <span class="reviewed">已评阅</span>
          </div>

          <!-- 筛选器 -->
          <div class="filter-options">
            <h4>答题卡</h4>
            <div style="margin:15px 20px">
                <label class="switch">
                <input type="checkbox" v-model="showWrongOnly">
                <span class="slider round"></span>
                </label>
                <span>仅显示错题</span>
            </div>
            <div style="margin:15px 20px">
                <label class="switch">
                <input type="checkbox" v-model="showSubjectiveOnly">
                <span class="slider round"></span>
                </label>
                <span>仅显示主观题</span>
            </div>
                  <!-- 提示用户颜色的含义 -->
            <div class="color-legend">
                <div class="legend-item">
                <span class="color-box correct"></span>
                <span>正确</span>
                </div>
                <div class="legend-item">
                <span class="color-box wrong"></span>
                <span>错误</span>
                </div>
                <div class="legend-item">
                <span class="color-box subjective"></span>
                <span>主观题</span>
                </div>
            </div>
          </div>
          <!-- 题号导航 -->
          <div class="question-navigation">
            <h4>题号导航</h4>
            <div class="question-numbers">
              <span v-for="(question, index) in questions" :key="index"
                    @click="scrollToQuestion(index)"
                    :class="{
                        'wrong-question': question.studentScore < question.score && question.type !== 'qna',
                        'correct-question': question.studentScore === question.score && question.type !== 'qna',
                        'subjective-question': question.type === 'qna'
                    }"
                    class="question-number">
                {{ index + 1 }}
              </span>
            </div>
          </div>
        </div>

        <!-- 右侧部分：分数条 + 题目详细作答 -->
        <div class="right-panel">
          <!-- 分数条 -->
          <div class="score-bar">
            <table>
              <thead>
                <tr>
                  <th>题号</th> 
                  <th v-for="(question, index) in questions" :key="'header' + index">{{ index + 1 }}</th>
                  <th>总分</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th>应得分</th>
                  <td v-for="(question, index) in questions" :key="'score' + index">{{ question.score }}</td>
                  <td class="total-score">{{ totalExpectedScore }}</td>
                </tr>
                <tr>
                  <th>实得分</th>
                  <td v-for="(question, index) in questions" :key="'studentScore' + index">{{ question.studentScore }}</td>
                  <td class="total-score">{{ totalStudentScore }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 题目展示 -->
          <div class="questions">
            <div v-if="questions.length === 0" class="empty-tips">
              <img src="@/assets/picture/notips.png" alt="暂未提交" class="no-data-img" />
              <p style="text-align:center; color: gray; margin-top: 10px;">尚未提交试卷</p>
            </div>
             <div v-else>
              <div v-for="(question, index) in filteredQuestions" :key="index" class="question" :id="'question-' + index">
                <div class="box-flex">
                  <h4>{{ index + 1 }}. {{ question.title }}（{{ question.score }}分）</h4>
                  <!-- 新增一个 actions 包裹 分数和星标按钮 -->
                  <div class="actions">
                    <span class="score-box">{{ question.studentScore }} / {{ question.score }}分</span>
                    <img
                      class="favorite-btn"
                      :src="question.is_star 
                        ? require('@/assets/picture/star-solid.png') 
                        : require('@/assets/picture/star.png')"
                      :alt="question.is_star ? '已收藏' : '未收藏'"
                      @click="toggleFavorite(question)"
                    />
                  </div>
                </div>

                <!-- 选择题 -->
                <ul v-if="question.options">
                  <li v-for="option in question.options" :key="option.key"
                      :class="{
                        'correct-answer': option.isCorrect,
                        'student-wrong': option.selected && !option.isCorrect,
                        'student-correct': option.selected && option.isCorrect
                      }">
                    <input type="radio" :checked="option.selected" disabled>
                    {{ option.text }}
                  </li>
                </ul>

                <!-- 简答题 -->
                <div v-if="question.type === 'qna'" class="subjective-answer">
                  <div class="student-answer">
                    <h5>学生作答：</h5>
                    <div v-html="question.studentAnswer"></div>
                  </div>
                  <div class="reference-answer">
                    <h5>参考答案：</h5>
                    <div v-html="question.correctAnswer"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import { ref, computed, onMounted } from 'vue';
import StuExamNavBar from '@/components/StuExamNavBar.vue';
import { fetchStuExamDetail,addQuestionFavorite, removeQuestionFavorites } from '@/services/api';
import { getUserInfo } from '@/services/user';
import { ElMessage } from "element-plus";


export default {
  components: { StuExamNavBar },
  props: {
    examId: [String, Number],
    semesterId: [String, Number]
  },
  setup(props) {
    const studentInfo = ref({
      name: '',
      number: '',
      class: '',
      avatar: ''
    });
    const questions = ref([]);
    const showWrongOnly = ref(false);
    const showSubjectiveOnly = ref(false);
    const rawExamStuFormat = ref([]);
    const paperId = ref(localStorage.getItem('currentPaperId'));
    const userId = ref(localStorage.getItem('id'));
    const stuExamId = ref(localStorage.getItem('stu_exam_id'));

    const removeHtmlTags = (text) => text?.replace(/<\/?[^>]+(>|$)/g, "") || "";

    const toggleFavorite = async (question) => {
      if (question.is_star) {
        // 取消收藏
        try {
          const res = await removeQuestionFavorites(question.qs_star_id);
          if (res.data.status === 1) {
            question.is_star = false;
            ElMessage.success('取消收藏成功');
          } else {
            // 万一 status 不是 1，也可以统一提示
            ElMessage.error(res.data.msg || '取消收藏失败');
          }
        } catch {
          ElMessage.error('取消收藏失败');
        }
      } else {
        // 添加收藏
        try {
          const res = await addQuestionFavorite({
            user_id: userId.value,
            qs_id: question.qs_id
          });
          if (res.data.status === 1) {
            question.is_star = true;
            question.qs_star_id = res.data.data.qs_star_id;
            ElMessage.success('收藏成功');
          } else {
            // status === 0 时用后端 msg
            ElMessage.error(res.data.msg);
          }
        } catch {
          ElMessage.error('收藏失败');
        }
      }
    };

   const fetchData = async () => {
      try {
        const userRes = await getUserInfo(userId.value);
        if (userRes.data.status === 1) {
          const user = userRes.data.data;
          studentInfo.value = {
            avatar: user.img_url,
            name: user.username,
            number: user.stu_number || 'N/A',
            class: user.university_name || '未知班级'
          };
        }
      } catch (err) {
        console.error("获取用户信息失败:", err.message);
      }

      try {
        const examRes = await fetchStuExamDetail(paperId.value, props.semesterId, stuExamId.value, userId.value);
        if (examRes.data.status === 1) {
          const data = examRes.data.data;
          rawExamStuFormat.value = data.examStuFormat || [];

          questions.value = data.qsList.flatMap(qsGroup =>
            qsGroup.items.map(item => ({
              title: removeHtmlTags(item.qs_title),
              qs_star_id: item.qs_star_id,
              is_star: item.is_star,
              score: item.q_score || 0,
              qs_id: item.qs_id,
              type: item.qs_type,
              isCorrect: item.is_getright,
              options: item.options?.map(opt => ({
                key: opt.option_id,
                text: removeHtmlTags(opt.option_content),
                selected: opt.stu_choosed,
                isCorrect: opt.is_right
              })) || [],
              studentAnswer: item.stu_ans || '',
              correctAnswer: item.qna_ans || '',
              studentScore: item.stu_score || 0
            }))
          );
        }
      } catch (err) {
        console.error("获取试卷作答信息失败:", err.message);
      }
    };
    const filteredQuestions = computed(() => {
      return questions.value.filter(q => {
        if (showWrongOnly.value && q.isCorrect === true) return false;
        if (showSubjectiveOnly.value && q.type !== 'qna') return false;
        return true;
      });
    });

    const totalExpectedScore = computed(() =>
      questions.value.reduce((sum, q) => sum + (q.score || 0), 0)
    );

    const totalStudentScore = computed(() =>
      questions.value.reduce((sum, q) => sum + (q.studentScore || 0), 0)
    );

    const formatScoreSummary = computed(() => {
      const summary = { single: 0, multi: 0, judge: 0, short: 0, total: 0 };
      for (const section of rawExamStuFormat.value) {
        if (section.format_content.includes('单选')) summary.single = section.stu_score;
        if (section.format_content.includes('多选')) summary.multi = section.stu_score;
        if (section.format_content.includes('判断')) summary.judge = section.stu_score;
        if (section.format_content.includes('简答')) summary.short = section.stu_score;
      }
      summary.total = summary.single + summary.multi + summary.judge + summary.short;
      return summary;
    });

    const scrollToQuestion = (index) => {
      document.getElementById(`question-${index}`)?.scrollIntoView({ behavior: "smooth" });
    };

    onMounted(() => {
      fetchData();
    });

    return {
      studentInfo,
      questions,
      showWrongOnly,
      showSubjectiveOnly,
      filteredQuestions,
      scrollToQuestion,
      totalExpectedScore,
      totalStudentScore,
      formatScoreSummary,
      removeHtmlTags,
      toggleFavorite,
    };
  }
};
</script>

<style scoped>
.actions {
  display: flex;
  align-items: center;
}
.favorite-btn {
  width: 28px;
  height: 28px;
  margin-left: 8px;
  margin-top: 10px;
  cursor: pointer;
}
.empty-tips {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;

}

.no-data-img {
  width: 200px;
  height: auto;
  opacity: 0.4;
}
.exam-review {
  display: flex;
  justify-content: center;
  background: #E3F2FD;
  padding: 20px;
}

.container {
  width: 85vw;
  padding: 20px;
  border-radius: 8px;
}

.content-layout {
  display: flex;
  background-color: #ffffff;
  min-width: 1000px; /* 添加最小宽度 */
}

/* 左侧面板 */
.left-panel {
  width: 300px; /* 固定宽度 */;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
}

.student-info {
  display: flex;
  align-items: center;
  background: #ffffff;
  padding: 15px;
  border-radius: 8px;
  position: relative; /* 使得绝对定位的元素相对于该元素定位 */
}

.reviewed {
  position: absolute;
  top: 50px; /* 距离上边缘 */
  right: 0px; /* 距离右边缘 */
  background: #42A5F5; /* 绶带背景色 */
  color: #fff; /* 白色字体 */
  font-weight: bold;
  padding: 5px 15px;
  transform: rotate(45deg); /* 使标签倾斜 */
  transform-origin: top right; /* 设置旋转中心点为右上角 */
  border-radius: 3px;
  font-size: 14px; /* 调整字体大小 */
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 15px;
}



/* 筛选器 */
.filter-options {
  margin: 20px 0;
  padding: 10px;
  background: #ffffff;
  border-radius: 8px;
}

.filter-options label {
  margin-right: 10px;
  cursor: pointer;
}

.switch {
  position: relative;
  display: inline-block;
  width: 34px;
  height: 20px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: 0.4s;
  border-radius: 50px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 12px;
  width: 12px;
  border-radius: 50%;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: 0.4s;
}

input:checked + .slider {
  background-color: #42A5F5;
}

input:checked + .slider:before {
  transform: translateX(14px);
}

/* 提示色球 */
.color-legend {
  display: flex;
  justify-content: space-around;
  padding: 10px;
  background: #ffffff;
  border-radius: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
}

.color-box {
  width: 15px;
  height: 15px;
  border-radius: 50%;
  margin-right: 10px;
}

.correct {
  background-color: #66BB6A; /* 绿色 */
}

.wrong {
  background-color: #EF5350; /* 红色 */
}

.subjective {
  background-color: #42A5F5; /* 蓝色 */
}

/* 题号导航 */
.question-navigation {
  background: #ffffff;
  padding: 15px;
  border-radius: 8px;
}

.question-numbers {
  margin: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  min-height: 100px; /* 题号导航最小高度 */
}

.question-number {
  width: 35px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-weight: bold;
  border-radius: 50%;
  cursor: pointer;
  transition: background 0.3s;
}

.wrong-question {
  background: #EF5350;
}

.wrong-question:hover {
  background: #D32F2F;
}

/* 正确题 - 绿色 */
.correct-question {
  background: #66BB6A;
}

.correct-question:hover {
  background: #388E3C;
}

/* 简答题 - 蓝色 */
.subjective-question {
  background: #42A5F5;
}

.subjective-question:hover {
  background: #1976D2;
}



/* 右侧面板 */
.right-panel {
  flex: 1 1 0; /* 改成允许缩放但优先保持初始宽度 */
  margin-right: 15px;
  min-width: 0;
}

.score-bar {
  background: #ffffff;
  padding: 15px;
  border-radius: 8px;
  margin-top: 15px;
  margin-bottom: 20px;
  overflow-x: auto; /* 保留这行，允许横向滚动 */
  max-width: 100%;   /* 限制最大宽度为容器宽度 */
}

.score-bar table {
  width: max-content;
  min-width: 100%; /* 也可以删除这一句，如果你希望宽度正好包裹内容 */
  border-collapse: collapse;
  text-align: center;
}
.score-bar th, .score-bar td {
  padding: 10px;
  border: 1px solid #ddd;
}

/* 表头样式 */
.score-bar thead {
  background: #42A5F5;
  color: white;
  font-weight: bold;
}

/* 让左侧列固定 */
.score-bar tbody th {
  background: #f5f7fa;
  font-weight: bold;
}



.questions {
  background: #ffffff;
  padding: 15px;
  border-radius: 8px;
}

/* 题目样式 */
.question {
  padding: 15px;
  border-bottom: 1px solid #ddd;
}

.question:last-child {
  border-bottom: none;
}

.score-box {
  display: inline-block;
  background: #42A5F5;
  color: #ffffff;
  padding: 5px 10px;
  border-radius: 5px;
  font-weight: bold;
  margin-top: 10px;
}

/* 选择题选项 */
ul {
  list-style: none;
  padding: 0;
}

li {
  padding: 8px;
  border-radius: 5px;
  margin: 5px 0;
  cursor: pointer;
}

.correct-answer {
  background: #84ff891f;
  color: #000000;
  border: solid 1px #00800040;
}

.student-wrong {
  background: #ff7e7e21;
  color: black;
  border: solid 1px #ff000029;
}

.student-correct {
  background: #85c6fa1a;
  color: black;
  border: solid 1px #257bb645;
}

/* 主观题样式 */
.subjective-answer {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.student-answer, .reference-answer {
  width: 50%;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
}

.box-flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
